package one.three.fortyFour;

public class Buffer {
	private Stack<String> left;
	private Stack<String> right;
	private int leftN;
	private int rightN;

	public Buffer() {
		left = new Stack<String>();
		right = new Stack<String>();
	}

	public int size() {
		return leftN + rightN;
	}

	public void insert(char c) {
		left.push(c + "");
		leftN++;
	}

	public char delete() {
		char c = left.pop().charAt(0);
		leftN--;
		return c;
	}

	public void left(int k) {
		if (k > leftN || leftN == 0) {
			return;
		}

		char[] tmp = new char[k];
		char[] temp = new char[rightN];

		for (int i = 0; i < k; i++) {
			tmp[i] = left.pop().charAt(0);
		}
		if (rightN > 0) {
			for (int i = 0; i < rightN; i++) {
				temp[i] = right.pop().charAt(0);
			}
		}

		for (int i = k - 1; i >= 0; i--) {
			right.push(tmp[i] + "");
		}

		if (rightN > 0) {
			for (int i = rightN - 1; i >= 0; i--) {
				right.push(temp[i] + "");
			}
		}

		leftN -= k;
		rightN += k;

	}

	public void right(int k) {
		if (k > rightN || rightN == 0) {
			return;
		}
		char[] tmp = new char[rightN];
		for (int i = rightN - 1; i >= 0; i--) {
			tmp[i] = right.pop().charAt(0);
		}
		for (int i = 0; i < k; i++) {
			left.push(tmp[i] + "");
		}
		right = new Stack<String>();
		for (int i = k; i < tmp.length; i++) {
			right.push(tmp[i] + "");
		}
		leftN += k;
		rightN -= k;
	}

	@Override
	public String toString() {
		StringBuilder s = new StringBuilder();
		Stack<String> leftTmp = new Stack<String>(left);
		char[] la = new char[leftN];
		for (int i = 0; i < leftN; i++) {
			la[i] = leftTmp.pop().charAt(0);
		}
		for (int i = leftN - 1; i >= 0; i--) {
			s.append(la[i]);
		}
		if (rightN > 0) {
			Stack<String> rightTmp = new Stack<String>(right);
			char[] ra = new char[rightN];
			for (int i = 0; i < rightN; i++) {
				ra[i] = rightTmp.pop().charAt(i);
			}
			for (int i = rightN - 1; i >= 0; i--) {
				s.append(ra[i]);
			}
		}
		return s.toString();
	}

	public static void main(String[] args) {
		Buffer b = new Buffer();
		b.insert('a');
		b.insert('b');
		b.insert('c');

		System.out.println(b);
		b.left(1);
		b.insert('d');
		System.out.println(b);
		b.right(1);
		b.insert('e');
		System.out.println(b);
	}
}
